<template>
  <div class="article-comments">
    <!-- 评论列表 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="已显示全部评论"
      @load="onLoad"
      :error="error"
      error-text="加载失败，请点击重试"
    >
      <CommentItem v-for="(item, i) in list" :key="i" :comment="item"></CommentItem>
    </van-list>
    <!-- 评论列表 -->

    <!-- 发布评论 -->
    <van-cell-group class="publish-wrap">
      <van-field clearable placeholder="请输入评论内容">
        <van-button slot="button" size="mini" type="info">发布</van-button>
      </van-field>
    </van-cell-group>
    <!-- /发布评论 -->
  </div>
</template>

<script>
import { getComments } from "@/api/comment.js";
import CommentItem from "./comment-item";
export default {
  name: "ArticleComment",
  props: {
    source: {
      type: [Number, String, Object],
      required: true
    },
    list: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      // list: [], // 评论列表
      loading: false, // 上拉加载更多的 loading
      finished: false, // 是否加载结束
      offset: null, // 获取下一页数据的标记
      limit: 10,
      error: false
    };
  },
  created() {
    this.onLoad();
  },
  methods: {
    async onLoad() {
      try {
        const { data } = await getComments({
          type: "a",
          source: this.source,
          offset: this.offset,
          limit: this.limit
        });
        // console.log(data);
        const { results } = data.data;
        this.list.push(...results);
        this.loading = false;
        this.$emit("onload-success", data.data.total_count);
        //  判断是否还有数据
        if (results.length) {
          this.offset = data.data.last_id; // 更新获取下一页数据的页码
        } else {
          this.finished = true; // 没有数据了，关闭加载更多
        }
      } catch (error) {}
    }
  },
  components: {
    CommentItem
  }
};
</script>

<style scoped lang="less">
.publish-wrap {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
}

.van-list {
  margin-bottom: 45px;
}
</style>